from django.shortcuts import render,redirect
from . import models
import hashlib
# Create your views here.

def index(request):
    return render(request,'index.html')
def login(request):
    if request.method =='GET':
        pass
        return render(request,'login.html')
    elif request.method == 'POST':
        context = {
            'message':''
        }
        # 用户提交表单
        username = request.POST.get('username')
        password=request.POST.get('password')
        # print(username,password)
        # 验证账户名密码
        user = models.User.objects.filter(name=username).first()
        if user:
            if user.password == user.hash_password:
                context['message'] = '登录成功'
                # 服务器设置sessionid和其他用户信息。sessionid(服务器给访问它的浏览器的身份证)自动生成的
                request.session['is_login'] = True
                request.session['username'] = user.name
                request.session['user_id'] = user.id
                return redirect('/index/')  # 返回响应中包含set-cookie(sessionid=asdffdhhgj),浏览器收到响应后会把sessionid 存到cookie中
            else:
                context['message'] = '密码错误，请重新输入'
                return render(request,'login.html',context=context)
        else:
            context['message'] = '用户未注册，请重新输入'
            return render(request,'login.html',context=context)
        # 登陆成功
        # print('登陆成功')
        # return redirect('/index/')

def register(request):
    if request.method =='GET':
        # 注册表单
        # 写数据库
        return  render(request,'register.html')
    elif request.method =='POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        # 简单后端表单验证（正则最合适）
        # 写入数据库
        # 相当于 'insert into login_user(name,password,email) values(%s,%s,%s)'% ('','','')
        user = models.User.objects.filter(email=email).first()
        if user :
            return render(request,'register.html',context={'message':'用户已经注册,点击此处去登录界面'})
        # 加密密码
        hash_password=_hash_password(password)
        try:
            user = models.User(name=username,password=password,hash_password=hash_password,email=email)
            user.save()
            print('注册成功')
            return render(request,'register.html',context={'message':'注册成功,去登录页面'})
        except Exception as e:
            print('保存失败')
            return redirect('/register/', context={'message': '注册失败'})

        # print('保存成功')
        # return redirect('/login/')
        # if not (username.strip() and password.strip() and email()):
        #     print('字段不能为空！')
        #     return  render('/register',context={'message':'字段不能为空！'})
        # if len(username) >20 or len (password)>20:
        #     print('用户名或密码长度不能超过20')
        #     return render('/register', context={'message': '字段不能为空！'})
def logout(request):
    """退出"""
    # w未登录时不让走退出函数

    # 清除session 登出
    request.session.flush()  # 清除此用户sessionid 对应的所有sessiondata
    # del  request.session['user_id'] # 清除某个session键值
    return redirect('/index/')

# 查询数据库 selecto * form login_user where name = %s and password=%s(username,password)
#    user=models.User.objects.filter(name=username,password=password).first()

def _hash_password(password):
    sha= hashlib.sha256()
    sha.update(password.encode('utf-8'))
    return sha.hexdigest()